package com.tgpms.web.element.controller;

import com.tgpms.auth.security.TokenService;
import com.tgpms.common.PageUtils;
import com.tgpms.common.R;
import com.tgpms.exception.ProjectException;
import com.tgpms.util.FTPUtil;
import com.tgpms.web.element.dao.WsDocDao;
import com.tgpms.web.element.entity.WsDoc;
import com.tgpms.web.element.entity.WsDocRel;
import com.tgpms.web.element.service.WsDocRelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Map;


/**
 * 附件关联表
 *
 * @author jl
 * @since 2020-07-13 11:33:18
 */
@Api(value = "WsDocRelController", tags = "附件关联表相关接口")
@RestController
@RequestMapping("/ev/wsdocrel")
public class WsDocRelController {
    @Autowired
    private WsDocRelService wsDocRelService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private WsDocDao wsDocDao;
    @Value("${ftpparam.wzyslocalloadfile}")
    private String wzyslocalloadfile;
    //ftp_url
    @Value("${ftpparam.url}")
    private String url;
    @Value("${ftpparam.port}")
    private Integer port;
    @Value("${ftpparam.username}")
    private String username;
    @Value("${ftpparam.password}")
    private String password;

    /**
     * 验收附件上传
     */
    @ApiOperation(value = "验收附件上传接口", notes = "验收附件上传接口", httpMethod = "POST")
    @PostMapping(value = "/importFile", headers = "content-type=multipart/form-data")
    public R importFile(@RequestParam("file") MultipartFile file, @RequestParam("docRelId") String docRelId, @RequestParam("docRelTable") String docRelTable,
                        @RequestParam("fileName")String fileName, HttpServletRequest request) {
        //获取上传人
        String insertName = tokenService.getUserName(request);
        try {
            wsDocRelService.importFile(file, docRelId, docRelTable,insertName,fileName);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ProjectException(e.getMessage());
        }
        return R.ok();
    }

    /**
     * 验收附件下载
     */
    @ApiOperation(value = "下载验收附件接口", notes = "下载验收附件接口", httpMethod = "POST")
    @PostMapping("/downFile")
    public ResponseEntity<byte[]> downFile(@RequestParam(value = "id") String id) {
        ResponseEntity<byte[]> entity = null;
        InputStream in = null;
        try {
            WsDoc wsDoc = wsDocDao.selectById(id);
            //先从本地文件夹取文件，有则本地下载，无则ftp下载
            String fileDir = wzyslocalloadfile;
            File dir = new File(fileDir);
            if (!dir.exists()){
                dir.mkdirs();
                in = FTPUtil.downloadFileForIn(url, port, username, password, wsDoc.getFilePath(), wsDoc.getNewName());
            }else {
                File excelFile = new File(dir.getAbsolutePath()+ File.separator+ wsDoc.getNewName());
                if(excelFile.exists()) {
                    in = new FileInputStream(excelFile);
                }else {
                    in = FTPUtil.downloadFileForIn(url, port, username, password, wsDoc.getFilePath(), wsDoc.getNewName());
                }
            }
            //设置浏览器响应
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment", wsDoc.getOriginalName());
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            HttpStatus status = HttpStatus.OK;
            //返回字节流IOUtils.toByteArray(in)
            entity = new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, status);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(in!=null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return entity;
    }

    /**
     * 带条件分页查询wsDocRel
     */
    @ApiOperation(value = "带条件分页查询wsDocRel", notes = "带条件分页查询wsDocRel", httpMethod = "GET")
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = wsDocRelService.queryPage(params);

        return R.ok(page);
    }


    /**
     * 根据主键查询wsDocRel
     */
    @ApiOperation(value = "根据主键查询wsDocRel", notes = "根据主键查询wsDocRel", httpMethod = "GET")
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") String id) {
        WsDocRel wsDocRel = wsDocRelService.getById(id);

        return R.ok(wsDocRel);
    }

    /**
     * 新增wsDocRel
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增wsDocRel", notes = "新增wsDocRel", httpMethod = "POST")
    public R save(@RequestBody WsDocRel wsDocRel) {
        wsDocRelService.save(wsDocRel);

        return R.ok();
    }

    /**
     * 修改wsDocRel
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改wsDocRel", notes = "修改wsDocRel", httpMethod = "PUT")
    public R update(@RequestBody WsDocRel wsDocRel) {
        wsDocRelService.updateById(wsDocRel);

        return R.ok();
    }

    /**
     * 删除wsDocRel
     */
    @DeleteMapping("/delete")
    @ApiOperation(value = "根据主键ids删除wsDocRel", notes = "根据主键ids删除wsDocRel", httpMethod = "DELETE")
    public R delete(@RequestBody String[] ids) {
        wsDocRelService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
